package com.xhj.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xhj.service.MsmService;
import com.xhj.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
@RequestMapping("/msm/")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @RequestMapping("send/{phoneNum}")
    public ResultEntity sendCode(@PathVariable("phoneNum") String phoneNum){
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        // 判断Redis中是否存在该手机号发送的验证码
        String code = operations.get(phoneNum);
        if (!StringUtils.isEmpty(code)) return ResultEntity.successWithoutData();
        String templateId = "f5e68c3ad6b6474faa8cd178b21d3377";
        String codeNum = "123456";
        boolean sendResult = msmService.send(phoneNum, templateId, codeNum);
        if (sendResult){
            // 把验证码存入Redis中，并设置5分钟过期时间
            operations.set(phoneNum,codeNum,5, TimeUnit.MINUTES);
            return ResultEntity.successWithoutData();
        }
        return ResultEntity.failedWithMessage("验证码发送失败!请重新发送");
    }

}
